using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Web;
using System.Xml.Serialization;
using System.Windows.Forms;
using System.Collections;
using System.IO;  
using System.Net;
using System.Xml;
using System.Xml.XPath;

namespace TwApp
{
    public partial class twapp : Form
    {
        private string username;
        private string password;
        private string seed = "harperRules!666";
        private int updateTime;
        private string url  = "http://www.flashandburn.net/twapp/";
        private int updateLen = 152;
        
        private int updateTimeMS;
        private string formTitle = "TwApp!";
        private twappConfig twappconfig = new twappConfig();
        private string configXMLName = "twappConfig_Config.xml";

        public twapp()
        {
            InitializeComponent();
            XmlSerializer x = new XmlSerializer(typeof(twappConfig));
 	
            // if it exists, deserialize XML config file
            FileStream fs = null;
            try
            {
                fs = new FileStream(configXMLName, FileMode.Open);

                XmlReader reader = new XmlTextReader(fs);
                twappconfig = (twappConfig)x.Deserialize(reader);
                try
                {
                    password = EncDec.Decrypt(twappconfig.password, seed);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                username = twappconfig.username;
                tbUsername.Text = username;
                tbPassword.Text = password;
                updateTime = twappconfig.updateTime;
                dUpdate.Text = updateTime + "";
            }
            catch (FileNotFoundException)
            {
                // ignore -- config file will be written
            }
            finally
            {
                if (fs != null)
                    fs.Close();
            }
        }

 

        private void button1_Click(object sender, EventArgs e)
        {
            if (username.Length>2)
            {
                if (tbUpdateText.Text != "")
                {
                    btnUpdate.Enabled = false;
                    string updateUrl = "http://twitter.com/statuses/update.json?status=" + tbUpdateText.Text;
                    HttpWebRequest request = WebRequest.Create(updateUrl) as HttpWebRequest;
                    request.Credentials = new NetworkCredential(username, password);
                    string result = "";
                    try
                    {
                        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                        {
                            StreamReader reader = new StreamReader(response.GetResponseStream());


                            // Load data  
                            result = reader.ReadToEnd();
                        }
                        btnUpdate.Enabled = true;
                        tbUpdateText.Text = "";
                        this.Text = formTitle + " :: Last updated at " + DateTime.Now;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Connection Error");
                        btnUpdate.Enabled = true;
                    }
                }
                else MessageBox.Show("Cowardly refusing to send empty update");
            }
            else MessageBox.Show("Please enter your username!");
        }

        private void lUpdate_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            
            if (username.Length > 2)
            {
                updateTimeline();
            }
            else MessageBox.Show("Please enter your username!");
            
            
        }

        private void parseUpdateXml(string xmlString)
        {
            XmlDocument doc = new XmlDocument();

            // Load data  
            doc.LoadXml(xmlString);
            XPathNavigator navigator = doc.CreateNavigator();
            // Set up namespace manager for XPath  
            XmlNamespaceManager ns = new XmlNamespaceManager(navigator.NameTable);
            

            // Get forecast with XPath  
            XmlNodeList nodes = doc.SelectNodes("//statuses/status", ns);//.Select("//rss/channel/item/yweather:forecast", ns); 
            
            listView1.Items.Clear();
            Hashtable ht = new Hashtable();
            foreach(XmlNode node in nodes)    
            {
                    XmlNodeList n = node.ChildNodes;
                    //created_at>
                    //id>
                    //text>
                    //relative_created_at>
                    
                    string created_at = n[0].InnerText;
                    string id= n[1].InnerText;
                    string text = n[2].InnerText;
                    string relative_created_at= n[3].InnerText;
                    XmlNodeList un = n[4].ChildNodes; 
                    string location= un[3].InnerText;
                    string description= un[4].InnerText;
                    string profile_image_url = un[5].InnerText;
                    string username = un[2].InnerText;
                    string name = un[1].InnerText;
                    string userid = un[0].InnerText;
                    string updatestring = name + " is: " + text;
                    Hashtable hi = new Hashtable();
                    hi.Add("text", text);
                    hi.Add("username", username);
                    hi.Add("name", name);
                    hi.Add("profile_image_url", profile_image_url);
                    hi.Add("relative_created_at", relative_created_at);
                    ListViewItem i = new ListViewItem();
                    i.SubItems.Add(updatestring);
                    i.SubItems.Add(relative_created_at);
                    i.Tag = hi;
                    //i.SubItems.Add(id);
                    listView1.Items.Add(i);
                    //ht.Add(id, i);
            }
            
        }
        private void updateTimeline()
        {
            
            Uri timelineUrl = new Uri("http://twitter.com/statuses/friends_timeline.xml");
            HttpWebRequest request = WebRequest.Create(timelineUrl) as HttpWebRequest;
            request.Credentials = new NetworkCredential(username, password);
            string result = "";
            try
            {
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream());
        

                    // Load data  
                    result = reader.ReadToEnd();
                }
                parseUpdateXml(result);
                
                 
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Connection Error");
            }
            
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            ListViewItem li = listView1.FocusedItem;
            Hashtable ht = (Hashtable)li.Tag;
            //Uri imgurl = new Uri(ht["profile_image_url"].ToString());
            pictureBox1.LoadAsync(ht["profile_image_url"].ToString());
            string name = ht["name"].ToString();
            string text = ht["text"].ToString();
            url = "http://twitter.com/"+ht["username"].ToString();
            string when = ht["relative_created_at"].ToString();
            tbStatus.Text = name + " says: " + text + " - " + when;
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(url);
        }

        
        private void textBox3_KeyUp(object sender, KeyEventArgs e)
        {
            
            tbCharsleft.Text = updateLen - tbUpdateText.Text.Length + "";
            
        }

        private void twapp_FormClosing(object sender, FormClosingEventArgs e)
        {
            XmlSerializer x = new XmlSerializer(typeof(twappConfig));
            TextWriter writer = new StreamWriter(configXMLName);
            x.Serialize(writer, this.twappconfig); 
        }

        private void tbUsername_TextChanged(object sender, EventArgs e)
        {
            twappconfig.username = tbUsername.Text;
            username = twappconfig.username;
        }

        private void tbPassword_TextChanged(object sender, EventArgs e)
        {
            twappconfig.password = EncDec.Encrypt(tbPassword.Text,seed);
            password = EncDec.Decrypt(twappconfig.password,seed);
        }

        private void btnAutoRefresh_Click(object sender, EventArgs e)
        {
            if (username.Length > 2)
            {
                if (!tmrRefresh.Enabled)
                {
                    if (updateTime == 0) updateTime = 5;
                    updateTimeMS = updateTime * (1000 * 60);
                    
                    tmrRefresh.Interval = updateTimeMS;
                    tmrRefresh.Start();
                    btnAutoRefresh.Text = "Stop!";
                    updateTimeline();
                }
                else
                {
                    tmrRefresh.Stop();
                    btnAutoRefresh.Text = "Start!";
                }
            }
            else MessageBox.Show("Please enter your username!");
        }

        private void dUpdate_SelectedItemChanged(object sender, EventArgs e)
        {
            updateTime = Convert.ToInt16(dUpdate.Text);
        }

        private void tmrRefresh_Tick(object sender, EventArgs e)
        {
            if (username != "")
            {
                updateTimeline();
            }
            else MessageBox.Show("Please enter your username!");
        }

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://www.nata2.org");
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("mail:harper@nata2.org");
        }
    }
}